import type { PromiseResult, PromiseAllCallback } from './index.d'
/**
 * promise 结果包装
 * @param promise 源数据
 * @returns 结果
 */
export function resultWrapper<T>(promise: Promise<T>) : Promise<PromiseResult<T>> {

  return new Promise(resolve => {
    promise
      .then(result => resolve({ success: true, result }))
      .catch(error => resolve({ success: false, error }))
  })
}

export function retryWrapper<T>(promise: Promise<T>, maxRetry = 2) : Promise<T> {
  return new Promise((resolve, reject) => {
    let retryCount = 1;
    const attempt = () => {
      promise.then(resolve)
      .catch(err => {
        if (maxRetry == 0) {
          reject(err);
        } else {
          console.log('重试请求')
          maxRetry--;
          setTimeout(() => attempt(), 1000 * retryCount++ + Math.random() * 1000)
        }
      })
    }
    attempt()
  })
}

/**
 * 自定义Promise.all支持进度更新
 *
 * @param promises
 * @param progressCallback
 * @returns
 */
export function promiseAllWithProgress<T>(promises: Promise<T>[], progressCallback: PromiseAllCallback<T>) {
  let successCount = 0;
  let errorCount = 0;
  const all = promises.length;
  const promiseWrappers = promises.map(promise => resultWrapper(promise));
  // 返回一个新的Promise，它将在所有给定的promises完成后解决
  return Promise.all<PromiseResult<T>>(promiseWrappers.map((promise, index) =>
    new Promise(resolve => {
      promise.then(result => {
        result.success ? successCount++ : errorCount++;
        // 更新进度
        progressCallback({ all, successCount, errorCount, ...result, index });
        resolve(result)
      })
    })
  ));
}

/**
 * 数组拆分
 * @param array
 * @param size
 * @returns
 */
export function chunkArray<T>(array: T[], size: number): T[][] {
  let result: T[][] = [];
  for (let i = 0; i < array.length; i += size) {
      let chunk = array.slice(i, i + size);
      result.push(chunk);
  }
  return result;
}


export async function promiseAllWithProgress2<T>(promises: Promise<T>[], progressCallback: PromiseAllCallback<T>) {
  let successCount = 0;
  let errorCount = 0;
  const all = promises.length;
  const promiseWrappers = promises.map(promise => resultWrapper(promise))
    .map((promise, index) => new Promise<PromiseResult<T>>(resolve => {
      promise.then(result => {
        result.success ? successCount++ : errorCount++;
        // 更新进度
        progressCallback({ all, successCount, errorCount, ...result, index });
        resolve(result)
      })
    }));

  const chunkPromiseArr = chunkArray(promiseWrappers, 6);
  return chunkPromiseArr.flatMap(async item => await Promise.all<PromiseResult<T>>(item))
}

  // for(let i = 0; i < chunkPromiseArr.length; i++) {


  // }


  // // 返回一个新的Promise，它将在所有给定的promises完成后解决
  // return Promise.all<PromiseResult<T>>(promiseWrappers.map((promise, index) =>
  //   new Promise(resolve => {
  //     promise.then(result => {
  //       result.success ? successCount++ : errorCount++;
  //       // 更新进度
  //       progressCallback({ all, successCount, errorCount, ...result, index });
  //       resolve(result)
  //     })
  //   })
  // ));
// }
